package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"zg3/live-broadcasts/api/request"
	"zg3/live-broadcasts/global"
	"zg3/live-broadcasts/internal/dao"
	"zg3/live-broadcasts/internal/model"
)

func LiveList(c *gin.Context) {

	var lives []model.Live
	if !dao.List(&lives) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "直播间列表查询成功",
		"data": lives,
	})
	return

}

func KillsLive(c *gin.Context) {
	var req request.KillsLiveReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var live model.Live
	dao.ConditionQuery(&model.Live{Id: req.LiveId}, &live)

	if live.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "直播间不存在",
			"data": false,
		})
		return
	}
	live.Status = 2
	if !dao.Update(&live) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "封禁失败",
			"data": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "封禁成功",
		"data": live,
	})
	return

}

func LiveUser(c *gin.Context) {
	var req request.LiveUserReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}

	var live model.Live
	dao.ConditionQuery(&model.Live{Id: req.LiveId}, &live)
	if live.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "直播间不存在",
			"data": false,
		})
		return
	}

	var liveUser []model.LiveUser
	global.DB.Where("live_id = ?", req.LiveId).Find(&liveUser)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询直播间成员成功",
		"data": liveUser,
	})
	return
}

func LiveLiveness(c *gin.Context) {
	var req request.LiveLivenessReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var live model.Live
	dao.ConditionQuery(&model.Live{Id: req.LiveId}, &live)
	var user model.User
	dao.ConditionQuery(&model.User{Id: live.UserId}, &user)
	var liveUser []model.LiveUser
	global.DB.Where("live_id = ?", req.LiveId).Find(&liveUser)
	userFansNum := user.FansNum
	liveUserNum := uint(5000)
	liveness := fmt.Sprintf("当前场次直播间粉丝活跃度是%v", 100-(userFansNum-liveUserNum)/userFansNum)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询当前场次直播间活跃度成功",
		"data": liveness,
	})
	return
}
